﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetHolder : MonoBehaviour {

    public static event System.Action OnRoundDecrease;
    public static event System.Action OnGameEnd;
    public static event System.Action OnArrowDecrease;

    public int targetCounts = 4;
    public float offsetX = 6;
    public float offsetY = 2;
    public GameObject targetPrefab;
    public int arrows = 20;

    private Vector3[] targetPos;
    private Target[] targetPool;
    private float nextGenerateTime = 2f;
    private float timeCopy;
    private bool isWaitForNextGeneration = true;


    private void Start()

    {
        GenerateTarget(false);
        BallControl.OnReleaseArrow += EndOfGame;
    }

    private void Update()
    {
        targetPool = FindObjectsOfType<Target>();
        if (targetPool.Length == 0)
        {
            if(isWaitForNextGeneration)
            {
                timeCopy = Time.time;
                isWaitForNextGeneration = false;
            }    
            
            if(Time.time - timeCopy > nextGenerateTime)
            {
                    GenerateTarget(false);
                    isWaitForNextGeneration = true;
                    if (OnRoundDecrease != null)
                        OnRoundDecrease();
            }
        }
    }

    void EndOfGame()
    {
        arrows--;
        if(OnArrowDecrease != null)
        {
            OnArrowDecrease();
        }
        Debug.Log("arrows: " + arrows);
        if(arrows == 0)
        {
            //Time.timeScale = 0;
            Debug.Log("GameOver");
            if(OnGameEnd != null)
            {
                OnGameEnd();
            }
        }
    }

    void GenerateTarget(bool isTargetMove)
    {
        targetPos = new Vector3[targetCounts];
        for (int i = 0; i < targetPos.Length; i++)
        {
            targetPos[i] = new Vector3(transform.position.x + offsetX * i, transform.position.y, transform.position.z);
        }

        for (int i = 0; i < targetPos.Length; i++)
        {
            GameObject target = GameObject.Instantiate(targetPrefab, targetPos[i], Quaternion.identity);
            target.transform.parent = this.transform;
            Target t = target.GetComponent<Target>();
            t.SetTargetVelocity();
            t.SetTargetMovement(isTargetMove);
        }
    }

    private void OnDestroy()
    {
        BallControl.OnReleaseArrow -= EndOfGame;
    }

}
